package com.forum.demo.controller;

import com.forum.demo.common.AppResult;
import com.forum.demo.common.ResultCode;
import com.forum.demo.config.AppConfig;
import com.forum.demo.model.Message;
import com.forum.demo.model.UserInfo;
import com.forum.demo.model.response.MessageResponse;
import com.forum.demo.services.impl.MessageServiceImpl;
import com.forum.demo.services.impl.UserServiceImpl;
import com.forum.demo.utils.checkFailUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageServiceImpl messageService;
    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @NonNull Long receiveUserId,
                          @NonNull String content) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //  不能给自己发站内信
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给自己发送站内信");
        }
        // 3. 校验接收者是否存在
        UserInfo receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null) {
            // 返回接收者状态不正常
            return AppResult.failed("接收者状态异常");
        }
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setContent(content);
        message.setReceiveUserId(receiveUserId);
        messageService.create(message);
        return AppResult.success();
    }

    @GetMapping("/getUnreadCount")
    public AppResult<Long> getUnreadCount (HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        Long num = messageService.selectUnreadCount(user.getId());
        return AppResult.success(num);
    }

    @GetMapping("/getAll")
    public AppResult<List<MessageResponse>> getAll(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        List<MessageResponse> messageResponses = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(messageResponses);
    }

    @PostMapping("/markRead")
    public AppResult<Long> markRead(HttpServletRequest request,@NonNull Long id) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        if (user.getId() != message.getReceiveUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        messageService.updateStateById(id, (byte) 1);
        Long num = messageService.selectUnreadCount(user.getId());
        return AppResult.success(num);
    }

    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                           @NonNull Long repliedId, @NonNull String content) {
        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            checkFailUtils.checkFail(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        System.out.println(existsMessage);
        if (existsMessage == null) {
            checkFailUtils.checkFail(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        if (existsMessage.getReceiveUserId() != user.getId()) {
            checkFailUtils.checkFail(ResultCode.FAILED_FORBIDDEN);
        }
        Message message = new Message();
        message.setContent(content);
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        messageService.reply(repliedId,message);
        return AppResult.success();
    }
}
